<?php

class ProjectController extends BaseController {

	/*
	|--------------------------------------------------------------------------
	| Default Home Controller
	|--------------------------------------------------------------------------
	|
	| You may wish to use controllers instead of, or in addition to, Closure
	| based routes. That's great! Here is an example controller method to
	| get you started. To route to this controller, just add the route:
	|
	|	Route::get('/', 'HomeController@showWelcome');
	|
	 */

	public function login() {
		$username = Input::get('username');
		$password = Input::get('password');
		$user = array("username" => $username, "password" => $password);
		var_dump($user);
		if (Auth::attempt($user)) {
			return Redirect::to("/index");
		} else {
			return Redirect::to("/login");
		}
	}

	public function signup() {
		$username = Input::get('username');
		$password = Input::get('password');
		$a = (Input::get('销售管理')=="on" ? true : false);
		$b = (Input::get('仓库管理')=="on" ? true : false);
		$c = (Input::get('财务管理')=="on" ? true : false);
		$d = (Input::get('经营分析')=="on" ? true : false);
		$e = (Input::get('基础数据')=="on" ? true : false);
		$f = (Input::get('系统维护')=="on" ? true : false);
		$user = User::create(array(
			"username" => $username,
			"password" => Hash::make($password),
			"销售管理" => $a,
			"仓库管理" => $b,
			"财务管理" => $c,
			"经营分析" => $d,
			"基础数据" => $e,
			"系统维护" => $f,
		));
		Auth::login($user);
		return Redirect::to('/index');
	}

	public function logout() {
		Auth::logout();
		return Redirect::to('/login');
	}

	public function gongsi() {
		$companys = Companys::orderby("id", "desc")->paginate(10);
		return View::make("gongsi")->with(array("title" => "公司管理", "companys" => $companys));
	}
	public function jichupost() {
		if (Input::get('厂商名') && Input::get('地址')) {
			$company = new Companys;
			$company->厂商名 = Input::get('厂商名');
			$company->地址 = Input::get('地址');
			$company->save();
		}
		return Redirect::to('/dashboard/jichu');
	}

	public function postpinpai() {
		$name = Input::get("name");
		$address = Input::get("address");
		// return $name.$address;
		$company = new Companys;
		$company->厂商名 = $name;
		$company->地址 = $address;
		// $row = DB::insert('insert into companys (`厂商名`, `地址`) values (?, ?)', array($name, $address));
		// return $company->save()->toSql();
		if ($company->save()) {
			return $this->makeResponse(200, null, $company);
		} else {
			return $this->makeResponse(500, '操作失败', null);
		}
	}

	public function delpinpai() {
		$delname = Input::get("delname");
		// return sizeof($delname);
		if (sizeof($delname) != 0) {
			$del = Companys::destroy($delname);
			if ($del) {
				return $this->makeResponse(200, null, $del);
			} else {
				return $this->makeResponse(500, '操作失败', null);
			}
		} else {
			return $this->makeResponse(404, '操作失败', null);
		}
		// return $delname;
		// return $delname;
		// return $name.$address;
		// $row = DB::insert('insert into companys (`厂商名`, `地址`) values (?, ?)', array($name, $address));
		// return $company->save()->toSql();
	}

	public function getcompanys() {
		$companys = Companys::select(DB::raw("厂商名 as DisplayText"), DB::raw("id as Value"))->get();
		return $this->makeResponse("OK", "Options", $companys);
	}

	public function getcars() {
		$companys = Cars::select(DB::raw("型号 as DisplayText"), DB::raw("id as Value"))->get();
		return $this->makeResponse("OK", "Options", $companys);
	}

	public function getcarslist() {
		$list = DB::table("cars")
			->select("cars.id", "cars.型号", "cars.公司", "cars.进货价格", "cars.出售价格", "cars.年份")
			->leftJoin("companys", function ($join) {
				$join->on("companys.id", "=", "cars.公司");
			})
			->get();

		return $this->makeResponse('OK', "Records", $list);
	}

	public function addcar() {
		$xinghao = Input::get("型号");
		$gongshi = Input::get("公司");
		$injiage = Input::get("进货价格");
		$outjiage = Input::get("出售价格");
		$year = Input::get("年份");
		$car = new Cars;
		$car->型号 = $xinghao;
		$car->公司 = $gongshi;
		$car->进货价格 = $injiage;
		$car->出售价格 = $outjiage;
		$car->年份 = $year;

		if ($car->save()) {
			return $this->makeResponse('OK', "Record", $car);
		}

	}

	public function editecar() {
		$id = Input::get("id");
		$xinghao = Input::get("型号");
		$gongshi = Input::get("公司");
		$injiage = Input::get("进货价格");
		$outjiage = Input::get("出售价格");
		$year = Input::get("年份");
		$car = Cars::find($id);
		$car->型号 = $xinghao;
		$car->公司 = $gongshi;
		$car->进货价格 = $injiage;
		$car->出售价格 = $outjiage;
		$car->年份 = $year;

		if ($car->save()) {
			return $this->makeResponse('OK');
		}

	}

	public function deletecar() {
		$id = Input::get("id");
		$car = Cars::find($id)->delete();

		if ($car) {
			return $this->makeResponse('OK');
		}

	}

	public function getcompanyslist() {
		$list = Companys::all();

		return $this->makeResponse('OK', "Records", $list);
	}

	public function addcompany() {
		$changshangming = Input::get("厂商名");
		$address = Input::get("地址");
		$companys = new Companys;
		$companys->厂商名 = $changshangming;
		$companys->地址 = $address;

		if ($companys->save()) {
			return $this->makeResponse('OK', "Record", $companys);
		}

	}

	public function editecompany() {
		$id = Input::get("id");
		$changshangming = Input::get("厂商名");
		$address = Input::get("地址");
		$companys = Companys::find($id);
		$companys->型号 = $changshangming;
		$companys->公司 = $address;

		if ($companys->save()) {
			return $this->makeResponse('OK');
		}

	}

	public function deletecompany() {
		$id = Input::get("id");
		$companys = Companys::find($id)->delete();

		if ($companys) {
			return $this->makeResponse('OK');
		}

	}

	public function getclientslist() {
		$list = Clients::all();

		return $this->makeResponse('OK', "Records", $list);
	}

	public function addclient() {
		$name = Input::get("姓名");
		$sex = Input::get("性别");
		$address = Input::get("地址");
		$phone = Input::get("电话");
		$age = Input::get("年龄");
		$client = new Clients;
		$client->姓名 = $name;
		$client->性别 = $sex;
		$client->地址 = $address;
		$client->电话 = $phone;
		$client->年龄 = $age;

		if ($client->save()) {
			return $this->makeResponse('OK', "Record", $client);
		}

	}

	public function editeclient() {
		$id = Input::get("id");
		$name = Input::get("姓名");
		$sex = Input::get("性别");
		$address = Input::get("地址");
		$phone = Input::get("电话");
		$age = Input::get("年龄");
		$client = Clients::find($id);
		$client->姓名 = $name;
		$client->性别 = $sex;
		$client->地址 = $address;
		$client->电话 = $phone;
		$client->年龄 = $age;

		if ($client->save()) {
			return $this->makeResponse('OK');
		}

	}

	public function deleteclient() {
		$id = Input::get("id");
		$clients = Clients::find($id)->delete();

		if ($clients) {
			return $this->makeResponse('OK');
		}

	}

	public function getmaxorderid() {
		$id = Input::get("id");
		$clients = Clients::find($id)->delete();

		if ($clients) {
			return $this->makeResponse('OK');
		}
	}

	public function addorder()
	{
		$clientid = Input::get("clientid");

		$day = date("Y-m-d");
		$sell = new Sell;
		$sell->客户 = $clientid;
		$sell->订货日期 = $day;
		$sell->交货日期 = $day;

		if($sell->save()){
			return $this->makeResponse("OK","Order",$sell);
		}
	}

	public function getorderlist()
	{
		$orderlist = DB::table("sell")
					->select("sell.*",
							"clients.姓名",
							"clients.性别",
							"clients.地址",
							"clients.电话",
							"clients.年龄")
					->leftJoin("clients","sell.客户","=","clients.id")
					->get();
		return $this->makeResponse("OK","Records",$orderlist);
	}

	public function getinorderlist()
	{
		$orderlist = DB::table("buy")
					->select("buy.*",
							"companys.厂商名",
							"companys.地址")
					->leftJoin("companys","buy.公司","=","companys.id")
					->get();
		return $this->makeResponse("OK","Records",$orderlist);
	}

	public function getselldetail()
	{
		$sellid = Input::get("sellid");

		$selldetaillist = SellDetail::where("订单号",$sellid)->get();

		return $this->makeResponse("OK","Records",$selldetaillist);
	}

	public function addselldetail()
	{
		$sellid = Input::get("sellid");
		$car = Input::get("车型");
		$number = Input::get("数量");
		$price = Input::get("售价");
		$isstore = Store::where("车型",$car)->first();
		if(is_null($isstore)||$isstore->数量==0){
			return $this->makeResponse("FALSE","not store");
		}
		if($isstore->数量>=$number){

			$selldetail = new SellDetail;
	
			$selldetail->订单号 = $sellid;
			$selldetail->车型 = $car;
			$selldetail->数量 = $number;
			$selldetail->售价 = $price;
	
			if($selldetail->save()){
				$isstore->数量=$isstore->数量 - $number;
				$isstore->save();
				return $this->makeResponse("OK","Record",$selldetail);
			}
			return $this->makeResponse("FALSE","selldetail",$selldetail);
		}else{
			return $this->makeResponse("FALSE","not enough");
		}
	}

	public function editeselldetail()
	{
		$id = Input::get("id");
		$sellid = Input::get("sellid");
		$car = Input::get("车型");
		$number = Input::get("数量");
		$price = Input::get("售价");

		$selldetail = SellDetail::find($id);
		$isstore = Store::where("车型",$selldetail->车型)->first();
		$isstore->数量 = $isstore->数量+$selldetail->数量;
		$isstore->save();
		$selldetail->delete();
		$isstore = Store::where("车型",$car)->first();
		if($isstore->数量<$number){
			return $this->makeResponse("FALSE","not enough");
		}
		$selldetail = new SellDetail;
		$selldetail->订单号 = $sellid;
		$selldetail->车型 = $car;
		$selldetail->数量 = $number;
		$selldetail->售价 = $price;
		if ($selldetail->save()) {
			$isstore->数量=$isstore->数量-$number;
			$isstore->save();
			return $this->makeResponse('OK');
		}
	}

	public function deleteselldetail()
	{
		$id = Input::get("id");
		$selldetail = SellDetail::find($id);
		$store = Store::where("车型",$selldetail->车型)->first();
		$store->数量 = $store->数量 + $selldetail->数量;
		$store->save();
		$selldetail->delete();
		return $this->makeResponse('OK');
	}


	public function addinorder()
	{
		$companyid = Input::get("companyid");

		$day = date("Y-m-d");
		$buy = new Buy;
		$buy->公司 = $companyid;
		$buy->订货日期 = $day;
		$buy->到货日期 = $day;

		if($buy->save()){
			return $this->makeResponse("OK","Order",$buy);
		}
	}

	public function getbuydetail()
	{
		$sellid = Input::get("buyid");

		$selldetaillist = BuyDetail::where("订单号",$sellid)->get();

		return $this->makeResponse("OK","Records",$selldetaillist);
	}

	public function addbuydetail()
	{
		$buyid = Input::get("buyid");
		$car = Input::get("型号");
		$number = Input::get("数量");
		$price = Input::get("价格");

		$store = Store::where("车型",$car)->first();

		if(!$store){
			$store = new Store;
			$store->车型 = $car;
			$store->数量 = $number;
			$store->save();
		}else{
			$store->数量 = $store->数量 + $number;
			$store->save();
		}

		$buydetail = new BuyDetail;

		$buydetail->订单号 = $buyid;
		$buydetail->型号 = $car;
		$buydetail->数量 = $number;
		$buydetail->价格 = $price;

		if($buydetail->save())
			return $this->makeResponse("OK","Record",$buydetail);
		return $this->makeResponse("FALSE","buydetail",$buydetail);
	}

	public function editebuydetail()
	{
		$id = Input::get("id");
		$buyid = Input::get("buyid");
		$car = Input::get("型号");
		$number = Input::get("数量");
		$price = Input::get("价格");

		$buydetail = BuyDetail::find($id);

		$isstore = Store::where("车型",$buydetail->型号)->first();
		$isstore->数量 = $isstore->数量-$buydetail->数量;
		$isstore->save();
		$buydetail->delete();
		$isstore = Store::where("车型",$car)->first();
		$buydetail = new BuyDetail;
		$buydetail->订单号 = $buyid;
		$buydetail->型号 = $car;
		$buydetail->数量 = $number;
		$buydetail->价格 = $price;
		if ($buydetail->save()) {
			$isstore->数量=$isstore->数量+$number;
			$isstore->save();
			return $this->makeResponse('OK');
		}
	}

	public function deletebuydetail()
	{
		$id = Input::get("id");

		$buydetail = BuyDetail::find($id);
		$store = Store::where("车型",$buydetail->型号)->first();
		$store->数量 = $store->数量 + $buydetail->数量;
		$store->save();
		$buydetail->delete();

			return $this->makeResponse('OK');
		
	}

	public function getstore()
	{
		$store = DB::table("store")->select("companys.厂商名",
			"cars.型号",
			"store.*")->leftJoin("cars","cars.id","=","store.车型")->leftJoin("companys",'companys.id',"=","cars.公司")->get();
		return $this->makeResponse('OK','Records',$store);
	}

	public function dbbackup()
	{
		$filename=date("Y-m-d_H-i-s")."-backup.sql"; 
		// 所保存的文件名 
		// header("Content-disposition:filename=".$filename); 
		// header("Content-type:application/octetstream"); 
		// header("Pragma:no-cache"); 
		// header("Expires:0"); 
		// 获取当前页面文件路径，SQL文件就导出到此文件夹内 
		$tmpFile = app_path().$filename; 
		// $str = "mysqldump -uroot -p123ysw --default-character-set=utf8 project > ".$tmpFile;
		// echo $str;
		// 用MySQLDump命令导出数据库 
		exec("mysqldump -uroot -p123ysw --default-character-set=utf8 project > ".$tmpFile); 
		
		$headers = array(
              'Content-Type: text/x-sql',
            );
		return Response::download($tmpFile,"dbbackup.sql",$headers);
	}

	public function shieryuechengben()
	{
		$t = time(); 
		$end= mktime(23,59,59,12,31,date("Y",$t));
		$yearend= date("Y-m-d H:i:s",$end);
		$start = mktime(0,0,0,1,1,date("Y",$t));
		$yearstart= date("Y-m-d H:i:s",$start);
		$chengben = BuyDetail::select(DB::raw("sum(数量*价格) as price"),DB::raw("date_format(created_at,'%m') as month"))->where("created_at",">=",$start)->where("created_at","<=",$yearend)
								->groupBy(DB::raw("date_format(created_at,'%Y%m')"))
								->get();
		$array = [0,0,0,0,0,0,0,0,0,0,0,0];
		foreach ($chengben as $key => $value) {
			
			$array[intval($value['month'])]=intval($value['price']);
		}
		return $array;
	}

	public function shieryueyingshou()
	{
		$t = time(); 
		$end= mktime(23,59,59,12,31,date("Y",$t));
		$yearend= date("Y-m-d H:i:s",$end);
		$start = mktime(0,0,0,1,1,date("Y",$t));
		$yearstart= date("Y-m-d H:i:s",$start);
		$chengben = SellDetail::select(DB::raw("sum(数量*售价) as price"),DB::raw("date_format(created_at,'%m') as month"))->where("created_at",">=",$start)->where("created_at","<=",$yearend)
								->groupBy(DB::raw("date_format(created_at,'%Y%m')"))
								->get();
		$array = [0,0,0,0,0,0,0,0,0,0,0,0];
		foreach ($chengben as $key => $value) {
			
			$array[intval($value['month'])]=intval($value['price']);
		}
		return $array;
	}

	public function shieryuechexing()
	{
		$t = time(); 
		$end= mktime(23,59,59,12,31,date("Y",$t));
		$yearend= date("Y-m-d H:i:s",$end);
		$start = mktime(0,0,0,1,1,date("Y",$t));
		$yearstart= date("Y-m-d H:i:s",$start);
		$chengben = DB::table("selldetail")->select(DB::raw("sum(数量) as number"),"cars.型号")->where("selldetail.created_at",">=",$start)->where("selldetail.created_at","<=",$yearend)
								->leftJoin("cars","cars.id","=","selldetail.车型")
								->groupBy("selldetail.车型")
								->get();
		$chengben = json_decode(json_encode($chengben),true);
		$array = [];
		$allarray = array();
		foreach ($chengben as $key => $value) {
			$allarray[] = [$value['型号'],intval($value['number'])];
		}
		// echo json_encode($array);
		// $array = [["fdf",434],["dfdf",434]];
		return $allarray;
		// return "[[“fdf”,434],[“dfdf“,434]]";
	}
}
